package cn.jn.lhm.part06;

import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousFileChannel;
import java.nio.channels.CompletionHandler;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;

import static cn.jn.lhm.part01.ByteBufferUtil.debugAll;

/**
 * @author lhm 2753914576@qq.com
 * @time 2023/4/19 - 22:40
 **/
@Slf4j
public class AioFileChannel {
    public static void main(String[] args) throws IOException {
        try (AsynchronousFileChannel fileChannel = AsynchronousFileChannel.open(Paths.get((AioFileChannel.class.getResource("/").getPath() + "data.txt").substring(1)), StandardOpenOption.READ)) {
            ByteBuffer buffer = ByteBuffer.allocate(16);

            log.info("read begin.....");
            fileChannel.read(buffer, 0, buffer, new CompletionHandler<Integer, ByteBuffer>() {
                @Override
                public void completed(Integer result, ByteBuffer attachment) {
                    log.info("read complete....");
                    attachment.flip();
                    debugAll(attachment);
                }

                @Override
                public void failed(Throwable exc, ByteBuffer attachment) {
                    exc.printStackTrace();
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.in.read();
    }
}
